// utils/socket.js

import { VUE_APP_WEBSOCKET_URL } from '@/config/index'
import { reactive } from 'vue'
import { useMainStore } from '@/store/store'
const main = useMainStore()
const state = reactive({
	ws: null,
	contime: 0,
	isConnected: false,
})

function initSocket() {
	try {
		const token = uni.getStorageSync('accessToken') || ''
		// const token = '15c719610b424e87bf7f5f7ca7a28c46'
		let url = token
			? `${VUE_APP_WEBSOCKET_URL}?token=${encodeURIComponent(token)}`
			: `${VUE_APP_WEBSOCKET_URL}`
		state.ws = uni.connectSocket({
			url: url,
			success() {
				console.log('WebSocket 连接成功')
			},
		})

		// 全局只绑定一次监听，避免重复绑定
		uni.onSocketOpen(() => {
			console.log('WebSocket连接已打开！')

			state.contime = 0
			state.isConnected = true

			const msg = JSON.stringify({
				method: 'OnConnection',
				token,
				mobileDevice: true,
			})
			sendMsg(msg)
		})

		uni.onSocketError(() => {
			state.isConnected = false
			reconnect()
		})

		uni.onSocketClose(() => {
			state.isConnected = false
		})

		uni.onSocketMessage(res => {
            console.log(res);
            console.log(456);
            console.log(123);
			const data = JSON.parse(res.data)
			switch (data.type) {
				case 'initMessage':
					console.log('收到初始化消息', data)
					break
				case 'multi-person-ordering':
                    console.log('data',data);
					main.setMultiPersonOrderingCart(data)
					break
				default:
					break
			}
		})
	} catch (e) {
		console.error(e)
	}
}

function sendMsg(msg) {
	if (state.isConnected) {
		console.log('发送消息')
		uni.sendSocketMessage({
			data: msg,
			fail: () => {
				reconnect()
			},
		})
	} else {
		console.warn('WebSocket未连接，消息未发送')
	}
}

function reconnect() {
	state.contime += 1
	if (state.contime <= 10) {
		if (state.contime >= 3) {
			uni.showToast({
				title: `IM正在尝试第${state.contime}次重连...`,
				icon: 'none',
			})
		}
		setTimeout(() => {
			initSocket()
		}, 3000) // 每次3秒重连
	} else {
		uni.showToast({
			title: 'IM通讯连接失败，请联系管理员',
			icon: 'none',
		})
	}
}

function closeSocket() {
	if (state.ws) {
		uni.closeSocket()
	}
	state.isConnected = false
}

export default {
	state,
	initSocket,
	sendMsg,
	closeSocket,
}
